package com.itlong.cloud.propertyapp.service.impl;

import com.itlong.cloud.POJO.DTO.app.property.app.PropertyAppDeviceInfoDTO;
import com.itlong.cloud.POJO.PO.PropertyAppDeviceGroupInfoPO;
import com.itlong.cloud.POJO.VO.app.property.PropertyAppGetUserDevicesListVO;
import com.itlong.cloud.app.dao.IAppDeviceDao;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.PropertyEquipTypeEnum;
import com.itlong.cloud.propertyapp.dao.IPropertyAppDeviceDao;
import com.itlong.cloud.propertyapp.service.IPropertyAppDeviceService;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.*;

/**
 * <desc>
 * 物业App设备信息业务处理接口实现类
 * </desc>
 *
 * @createDate 2020/01/13
 */
@Service
public class PropertyAppDeviceServiceImpl implements IPropertyAppDeviceService {
    private static final Logger LOG = LoggerFactory.getLogger(PropertyAppDeviceServiceImpl.class);

    @Autowired
    RedisService redisService;

    @Autowired
    IPropertyAppDeviceDao iPropertyAppDeviceDao;

    @Autowired
    IAppDeviceDao iAppDeviceDao;

    /**
     * <desc>
     * 物业APP用户获取设备列表
     * <desc/>
     *
     * @param propertyAppDeviceInfoDTO 获取用户设备信息相关参数
     * @return
     * @author Juguang.S
     * @createDate 2020-01-13
     */
    @Override
    public Map<String, Object> getDeviceList(PropertyAppDeviceInfoDTO propertyAppDeviceInfoDTO) throws Exception {
        List<PropertyAppGetUserDevicesListVO> unGroupNewList = new ArrayList<>();
        String userId = propertyAppDeviceInfoDTO.getUserId();
        String projectId = propertyAppDeviceInfoDTO.getProjectId();
        Map<String,Object> resultMap = (Map<String, Object>) redisService.getObject(RedisConstant.REDIS_PROPERTY_APP_USER_DEVICE_CACHE + userId + projectId, HashMap.class);
//        Map<String,Object> resultMap = new HashMap<>();
        //如果resultMap为空，重新从数据库读取信息并设置缓存
        if (resultMap==null || resultMap.isEmpty()) {
            resultMap = new HashMap<>();
            //查询用户所有设备信息
            List<PropertyAppGetUserDevicesListVO> allDeviceInfo = iPropertyAppDeviceDao.getPropertyAppUserAllDeviceInfo(projectId);
            String commonFloor = iPropertyAppDeviceDao.getCommonFloorByUserIdAndProjectId(userId,projectId);
            if (allDeviceInfo != null) {
                for (PropertyAppGetUserDevicesListVO devicesInfoVO : allDeviceInfo) {
                    Integer deviceType = Integer.valueOf(devicesInfoVO.getDeviceUnique().substring(8, 9));
                    devicesInfoVO.setSubUniques(devicesInfoVO.getDeviceUnique());
                    switch (PropertyEquipTypeEnum.getByEquipType(deviceType)) {
                        case ELEVATOR:
                            Map<String, String> floorMap = iPropertyAppDeviceDao.getElevatorFloorInfo(devicesInfoVO.getDeviceUnique(), devicesInfoVO.getFloorNo(), devicesInfoVO.getFloorNoMax());
                            if (floorMap != null) {
                                //由于物业用户有所有设备所有楼层权限
                                devicesInfoVO.setLiveFloor(floorMap.get("naturalFloor"));
                                devicesInfoVO.setLiveLogicalFloor(floorMap.get("logicalFloor"));
                                Set<String> floorSet = new HashSet<String>();
                                //设置待选居住楼层名称
                                if (StringUtils.isNotBlank(floorMap.get("naturalFloor"))) {
                                    List<String> lf = Arrays.asList(StringHandlerUtil.splitString(floorMap.get("naturalFloor")));
                                    for (String l : lf) {
                                        floorSet.add(l);
                                    }
                                }
                                if(!floorSet.isEmpty()) {
                                    Map<String, Object> floors = iPropertyAppDeviceDao.getOrderFloors(floorSet, devicesInfoVO.getDeviceUnique());
                                    devicesInfoVO.setLiveFloor(StringHandlerUtil.getNullOrStringForObject(floors.get("floors")));
                                    devicesInfoVO.setLiveLogicalFloor(StringHandlerUtil.getNullOrStringForObject(floors.get("floorsName")));
                                }
                                //设置楼层权限
                                devicesInfoVO.setDeviceAuth(StringHandlerUtil.filterLastComma(StringHandlerUtil.getAuthCodeBynNturalFloors(devicesInfoVO.getLiveFloor())).toUpperCase());
                            }
                            if(StringUtils.isNotBlank(commonFloor)){
                                Map<String,Object> commanFloors = JsonUtil.toObject(commonFloor,HashMap.class);
                                if(commanFloors.containsKey(devicesInfoVO.getDeviceUnique())){
                                    devicesInfoVO.setCommonChoiceFloor(commanFloors.get(devicesInfoVO.getDeviceUnique()).toString());
                                    devicesInfoVO.setLiveChoiceFloor(commanFloors.get(devicesInfoVO.getDeviceUnique()).toString());
                                }
                            }
                            //设置过期时间
                            try {
                                devicesInfoVO.setValiTime(DateUtil.formatStringToDate(
                                        StringHandlerUtil.filterLastComma(devicesInfoVO.getValiTime()), DateUtil.YYMMDDHHMMSS).getTime() + "");
                            } catch (ParseException e) {
                                LOG.error("【电梯有效时间转换失败】");
                            }
                            //检索电梯是否是云电梯，如果是则查询是否绑定控制器
                            if (devicesInfoVO.getProperType().equals("2")) {
                                Map<String, Object> controlls = iPropertyAppDeviceDao.getControllerDeviceUniqueByElevatorDeviceUniques(devicesInfoVO.getDeviceUnique(), projectId);
                                if (controlls != null && controlls.get("groupConId") != null) {
                                    devicesInfoVO.setGroupConId(controlls.get("groupConId").toString());
                                    devicesInfoVO.setRelatedDeviceId(controlls.get("deviceUnique").toString());
                                }
                                // 需要判断云电梯是否开启蓝牙
                                if (devicesInfoVO.getIsBluetoothElevator() == 1) {
                                    devicesInfoVO.setProperType("1,2");
                                }
                            }
                            devicesInfoVO = (PropertyAppGetUserDevicesListVO)StringHandlerUtil.formatString(devicesInfoVO);
                            unGroupNewList.add(devicesInfoVO);
                            break;
                        case ENTRANCE:
                            devicesInfoVO.setDeviceAuth("8");
                            //设置过期时间
                            try {
                                devicesInfoVO.setValiTime(DateUtil.formatStringToDate(
                                        StringHandlerUtil.filterLastComma(devicesInfoVO.getValiTime()), DateUtil.YYMMDDHHMMSS).getTime() + "");
                            } catch (ParseException e) {
                                LOG.error("【门禁有效时间转换失败】");
                            }
                            devicesInfoVO = (PropertyAppGetUserDevicesListVO)StringHandlerUtil.formatString(devicesInfoVO);
                            unGroupNewList.add(devicesInfoVO);
                            break;
                        case CLOUD_INTERCOM:
                            //查询向灵云注册的设备的账号
                            if(devicesInfoVO.getSystemType().equals("2")){
                                devicesInfoVO.setClientAccount(iPropertyAppDeviceDao.getDeviceAccount(devicesInfoVO.getDeviceUnique()));
                            }
                            //设置过期时间
                            try {
                                devicesInfoVO.setValiTime(DateUtil.formatStringToDate(
                                        StringHandlerUtil.filterLastComma(devicesInfoVO.getValiTime()), DateUtil.YYMMDDHHMMSS).getTime() + "");
                            } catch (ParseException e) {
                                LOG.error("【云对讲有效时间转换失败】");
                            }
                            devicesInfoVO = (PropertyAppGetUserDevicesListVO)StringHandlerUtil.formatString(devicesInfoVO);
                            unGroupNewList.add(devicesInfoVO);
                            break;
                    }
                }
                resultMap.put("unGroupAry",unGroupNewList);
            }
            //获取用户在指定项目下设备信息
            String deviceOrder = iPropertyAppDeviceDao.getPropertyAppUserDeviceInfo(userId, projectId);
            //先处理外围设备排序相关问题
            List<String> groupListByMake = new ArrayList<>();
            if (StringUtils.isNotEmpty(deviceOrder) && allDeviceInfo != null) {
                unGroupNewList = new ArrayList<>();
                String[] deviceOrderArr = StringHandlerUtil.splitString(deviceOrder);
                for (String order : deviceOrderArr) {
                    //先判断排序中所遍历的是否是G开头的组信息，若是则需查询组内信息
                    if (order.startsWith("G")) {
                        groupListByMake.add(order);
                        Map<String,String> groupMap = iPropertyAppDeviceDao.getGroupInfo(order);
                        if(groupMap!=null){
                            PropertyAppGetUserDevicesListVO vo = new PropertyAppGetUserDevicesListVO();
                            vo.setDeviceUnique(groupMap.get("groupId"));
                            vo.setDeviceName(groupMap.get("groupName"));
                            vo.setDeviceType("0");
                            vo.setDeviceCount(groupMap.get("groupOrder").split(",").length+"");
                            vo.setSubUniques(groupMap.get("groupOrder"));
                            vo = (PropertyAppGetUserDevicesListVO)StringHandlerUtil.formatString(vo);
                            unGroupNewList.add(vo);
                        }
                    }else{
                        for (PropertyAppGetUserDevicesListVO info : allDeviceInfo) {
                            if (info.getDeviceUnique().equals(order)) {
                                info.setSubUniques(info.getDeviceUnique());
                                info = (PropertyAppGetUserDevicesListVO)StringHandlerUtil.formatString(info);
                                unGroupNewList.add(info);
                                continue;
                            }
                        }
                    }
                }
                resultMap.put("unGroupAry",unGroupNewList);
            }
            //查询用户在指定项目下的设备分组情况
            if(groupListByMake!=null && groupListByMake.size()==0){
                groupListByMake = null;
            }
            List<PropertyAppDeviceGroupInfoPO> groupList = iPropertyAppDeviceDao.getPropertyAppUserGroupInfo(userId, projectId,groupListByMake) == null ? new ArrayList<>() : iPropertyAppDeviceDao.getPropertyAppUserGroupInfo(userId, projectId,groupListByMake);
            //处理有分组的设备排序相关逻辑
            List<Map<String,Object>> groupAry = new ArrayList<>();
            for (PropertyAppDeviceGroupInfoPO groupInfo : groupList) {
                List<PropertyAppGetUserDevicesListVO> groupNewList = new ArrayList<>();
                if (StringUtils.isNotEmpty(groupInfo.getGroupOrder())) {
                    String[] deviceGroupOrderArr = StringHandlerUtil.splitString(groupInfo.getGroupOrder());
                    for (String groupOrder : deviceGroupOrderArr) {
                        for (PropertyAppGetUserDevicesListVO info : allDeviceInfo) {
                            if (info.getDeviceUnique().equals(groupOrder)) {
                                info = (PropertyAppGetUserDevicesListVO) StringHandlerUtil.formatString(info);
                                groupNewList.add(info);
                                continue;
                            }
                        }
                    }
                    //排除设备禁用后的分组设备数量
                    List<PropertyAppGetUserDevicesListVO> unGroupNewList1 = (List<PropertyAppGetUserDevicesListVO>) resultMap.get("unGroupAry");
                    if(!unGroupNewList1.isEmpty()){
                        for(int i = unGroupNewList1.size()-1; i>=0; i--){
                            if(unGroupNewList1.get(i).getDeviceUnique().equals(groupInfo.getGroupId())){
                                unGroupNewList1.get(i).setDeviceCount(groupNewList.size()+"");
                                if(groupNewList.size()==0){
                                    unGroupNewList1.remove(i);
                                }
                            }
                        }
                        resultMap.put("unGroupAry",unGroupNewList1);
                    }
                    Map<String, Object> groupMap = new HashMap<>();
                    groupMap.put("groupId", groupInfo.getGroupId());
                    groupMap.put("groupName", groupInfo.getGroupName());
                    groupMap.put("groupCount", groupNewList.size());
                    groupMap.put("subDeviceAry", groupNewList);
                    groupAry.add(groupMap);
                }
            }
            resultMap.put("groupAry",groupAry);
            //将所组装设备信息放至缓存
            redisService.set(RedisConstant.REDIS_PROPERTY_APP_USER_DEVICE_CACHE + userId + projectId,
                    RedisConstant.REDIS_APP_USER_DEVICE_CACHE_TIME, resultMap);
        }
        return resultMap;
    }

}
